#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from database import db_manager

def list_characters():
    """列出所有角色"""
    result = db_manager.execute_query(
        'SELECT id, name, account_id FROM characters ORDER BY account_id, created_at DESC'
    )
    print('所有角色:')
    for r in result:
        print(f'ID: {r["id"]}, 名称: {r["name"]}, 账号ID: {r["account_id"]}')
    return result

def delete_character(char_id):
    """删除指定角色"""
    try:
        affected = db_manager.execute_update(
            'DELETE FROM characters WHERE id = %s AND account_id = 1', 
            (char_id,)
        )
        if affected > 0:
            print(f'角色 {char_id} 删除成功')
        else:
            print(f'角色 {char_id} 删除失败或不存在')
        return affected > 0
    except Exception as e:
        print(f'删除角色失败: {e}')
        return False

if __name__ == '__main__':
    # 列出角色
    characters = list_characters()
    
    # 删除最后3个角色（保留7个）
    if len(characters) > 7:
        print(f'\n当前有 {len(characters)} 个角色，删除最后 {len(characters) - 7} 个...')
        for i in range(len(characters) - 7):
            char_id = characters[i]['id']
            char_name = characters[i]['name']
            print(f'删除角色: {char_name} (ID: {char_id})')
            delete_character(char_id)
    
    print('\n删除后的角色列表:')
    list_characters()